<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色组</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getAuthGroupList">
            <el-button slot="append" type="primary" icon="el-icon-search" @click="getAuthGroupList" ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="authGroupList" border style="width: 100%">
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="title" label="名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column  label="状态">
          <template slot-scope="scope">
          <el-tag type="danger" size="mini" v-if="scope.row.status == 0">禁用</el-tag>
          <el-tag type="success" size="mini" v-else>启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-s-unfold" size="mini" @click="getAuthRule(scope.row.id)">分配权限</el-button>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getEditAuthGroup(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delAuthGroup(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible"   width="30%"  @close="addHandleClose">
      <el-form :model="addAuthGroupForm" ref="addAuthGroupFormRef" :rules="addAuthGroupFormRules" label-width="70px">
        <el-form-item label="名称" prop="title">
          <el-input v-model="addAuthGroupForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addAuthGroupForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAuthGroup">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色组 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible"   width="30%"  @close="editHandleClose">
      <el-form :model="editAuthGroupForm" ref="editAuthGroupFormRef" :rules="editAuthGroupFormRules" label-width="70px">
        <el-form-item label="名称" prop="title">
          <el-input v-model="editAuthGroupForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editAuthGroupForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAuthGroup">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="authdialogFormVisible" @close="setRightDialogClosed">
          <el-tree
            :data="authRuleList"
            :props="defaultProps"
            ref="treeRef"
            show-checkbox
            node-key="id"
            :default-checked-keys="selectAuthRule"
            :default-expand-all="true">
          </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="authdialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      }],
      authRuleList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      authGroupList: [],
      total: 0,
      // 是否显示添加角色对话框
      addDialogVisible: false,
      addAuthGroupForm: {
        title: '',
        description: ''
      },
      // 验证添加表单
      addAuthGroupFormRules: {
        title: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 是否显示添加角色对话框
      editDialogVisible: false,
      editAuthGroupForm: {},
      // 验证添加表单
      editAuthGroupFormRules: {
        title: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      authdialogFormVisible: false,
      // 被选中的权限
      selectAuthRule: [],
      // 修改权限id
      editAuthGroupId: 0
    }
  },
  created() {
    this.getAuthGroupList()
    this.getAuthRuleList()
  },
  methods: {
    async getAuthGroupList () {
      const { data: res } = await this.$http.get(this.GLOBAL.authGroupList, {
        params: this.queryInfo
      })
      if (res.status !== 200) return this.$message.error(res.info)
      // console.log(res)
      this.authGroupList = res.data.authGroupList
      this.total = res.data.total
    },
    async getAuthRuleList () {
      const { data: res } = await this.$http.get(this.GLOBAL.authRuleList, {
        params: { status: 1 }
      })
      if (res.status !== 200) return false
      this.authRuleList = res.data.authRuleList
      // console.log(this.authRuleList)
    },
    // 每页条数改变时
    handleSizeChange (pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getAuthGroupList()
    },
    // 分页改变时触发
    handleCurrentChange (pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getAuthGroupList()
    },
    // 关闭添加角色对话框
    addHandleClose () {
      this.addDialogVisible = false
      // 清空表单
      this.$refs.addAuthGroupFormRef.resetFields()
    },
    // 添加角色组
    addAuthGroup () {
      this.$refs.addAuthGroupFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(this.GLOBAL.addAuthGroup, this.addAuthGroupForm)
        if (res.status !== 200) {
          return this.$message.error(res.info)
        }
        this.$message.success(res.info)
        this.addDialogVisible = false
        // 清空表单
        this.$refs.addAuthGroupFormRef.resetFields()
        // 从新获取列表
        this.getAuthGroupList()
      })
    },
    // 获取角色组信息
    async getEditAuthGroup (id) {
      const { data: res } = await this.$http.get(this.GLOBAL.getAuthGroup, {
        params: { id: id }
      })
      if (res.status !== 200) return this.$message.error(res.info)
      this.editAuthGroupForm = res.data.editAuthGroupForm
      this.editDialogVisible = true
    },
    // 关闭编辑框时触发
    editHandleClose () {
      // 隐藏编辑对话框
      this.editDialogVisible = false
      // 清空编辑表单
      this.$refs.editAuthGroupFormRef.resetFields()
    },
    // 保存编辑信息
    async editAuthGroup () {
      const { data: res } = await this.$http.post(this.GLOBAL.saveAuthGroup, this.editAuthGroupForm)
      if (res.status !== 200) return this.$message.error(res.info)
      this.$message.success(res.info)
      // 重置表单
      this.$refs.editAuthGroupFormRef.resetFields()
      // 关闭弹窗
      this.editDialogVisible = false
      // 重新获取数据
      this.getAuthGroupList()
    },
    // 删除角色组
    async delAuthGroup (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(() => {})
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 请求接口进行删除
      const { data: res } = await this.$http.post(this.GLOBAL.delAuthGroup, { id: id })
      // 删除失败
      if (res.status !== 200) return this.$message.error(res.info)
      // 提示信息
      this.$message.success(res.info)
      // 重新获取列表
      this.getAuthGroupList()
    },
    // 分配权限
    async getAuthRule (id) {
      // 获取角色权限组
      const { data: res } = await this.$http.get(this.GLOBAL.selectAuthGroup, {
        params: { id: id }
      })
      if (res.status !== 200) {
        return this.$message.error(res.info)
      }
      // 保存所选择id
      this.editAuthGroupId = id
      // 递归获取三级节点id
      this.authdialogFormVisible = true
      this.selectAuthRule = res.data.selectAuthRule
    },
    // 权限对话框关闭事件
    setRightDialogClosed () {
      // 清空所有选中的控件节点
      this.$refs.treeRef.setCheckedKeys([])
      this.selectAuthRule = []
      this.editAuthGroupId = 0
    },
    // 保存角色权限
    async allotRights () {
      if (this.editAuthGroupId === 0) return this.$message.info('请选择角色')
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), // 获取选中状态的节点id
        ...this.$refs.treeRef.getHalfCheckedKeys() // 获取半选中状态节点id（选中状态的父级id）
      ]
      // console.log(keys)
      // 合并选中节点id
      const ruleIds = keys.join(',')
      // 保存角色所拥有的权限id
      const { data: res } = await this.$http.post(this.GLOBAL.saveAuthGroupRolePermission, { id: this.editAuthGroupId, ruleIds: ruleIds })
      if (res.status !== 200) return this.$message.error(res.info)
      this.$message.success(res.info)
      // 关闭对话框
      this.authdialogFormVisible = false
      // 清空所选中控件节点
      this.setRightDialogClosed()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
